package com.xw.picture.analysis.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * 图片工具类
 *
 * @author wuwei_vendor
 */
@Slf4j
public class ImageUtil {

    /**
     * 将base64字符串，生成文件
     */
    public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            //判断文件目录是否存在
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            log.error("Exception = ",e);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    log.error("IOException = ",e1);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    log.error("IOException = ",e1);
                }
            }
        }
        return file;
    }


    /**
     * 获取Base64编码字符串
     *
     * @param ins 图片流
     * @return Base64编码字符串
     */
    public static String getImageBase64(InputStream ins) {
        byte[] data;
        String imageBase64 = null;
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = ins.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            data = outStream.toByteArray();
            imageBase64 = Base64.getEncoder().encodeToString(data);
            ins.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return imageBase64;
    }

    /**
     * 获取文件名
     *
     * @param fileName 文件全路径
     * @return 文件名
     */
    public static String getFileName(String fileName) {
        String[] temp = fileName.split("[\\\\/]");
        fileName = temp[temp.length - 1];
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /**
     * @param separators 符号
     * @return 特殊符号转译
     */
    public static String getSeparators(String separators) {
        switch (separators) {
            case ".":
                return "\\.";
            case "$":
                return "\\$";
            case "^":
                return "\\^";
            case "|":
                return "\\|";
            case "{":
                return "\\{";
            case "}":
                return "\\}";
            case "[":
                return "\\[";
            case "]":
                return "\\]";
            case "(":
                return "\\(";
            case ")":
                return "\\)";
            case "*":
                return "\\*";
            case "+":
                return "\\+";
            case "?":
                return "\\?";
            case "\\":
                return "\\\\";
            case " ":
                return "\\s";

            default:
                return separators;
        }
    }


    /**
     * 根据网络图片URL获取base64字节码
     *
     * @return base64图片
     */

    public static String getImageBase64ByUrl(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url.trim()).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return ImageUtil.getImageBase64(connection.getInputStream());
            }
        } catch (Exception e) {
            log.error("Get url: {}, error.", url, e);
        }
        //IVAAPIGW-362 图片下载失败问题，如果为null，则会引起viper接口bad request，因此修改为null字符串
        return "null";
    }

    public static byte[] read(InputStream in) {
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            byte[] data = new byte[10 * 1024];
            int count;
            while ((count = in.read(data)) != -1) {
                bo.write(data, 0, count);
            }
            return bo.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage());
            return new byte[0];
        } finally {
            try {
                in.close();
            } catch (IOException ignored) {
            }
        }
    }


//    public static String encode(byte[] bytes){
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(bytes).replace("\n", "").replace("\r", "");
//    }

    //十六进制字符串转byte[]
    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    //十六进制字符串转BASE64
    public static String hexToString(String hex) {
        String result = "null";
        try {
            result = Base64.getEncoder().encodeToString(hexStringToByteArray(hex));
        } catch (Exception ignored) {
        }
        return result;
    }

    public static void main(String...args){

    }
}
